<template>
	<basic-container>
		<el-container style="height:100%;">
			<el-container style="flex:none;">
				<el-header style="width:240px;border-right:1px solid #eeeeee;">
					<el-button type="primary" icon="el-icon-edit" size="small" style="margin-top:14px;" @click="handleRoleFormOpen('新增')"
						v-if="permission.addBtn">新增</el-button>
				</el-header>
				<el-aside style="height:100%;width:240px;border-top:1px solid #eeeeee;border-right:1px solid #eeeeee;">
					<el-menu class="el-menu-vertical-demo">
						<template>
							<el-menu-item v-for="(item, idx) in role.data" :index="idx + ''" :key="item.value" @click="handleRoleSelect(item.value)">
								<span>
									<i class="el-icon-menu"></i>
									<span slot="title">{{item.label}}</span>
								</span>
								<span style="float:right;">
									<el-button type="text" @click="handleRoleFormOpen('修改', item.value)"
										v-if="permission.editBtn">修改</el-button>
									<el-button type="text" @click="handleRoleDel(item, idx)"
										v-if="permission.delBtn">删除</el-button>
								</span>
							</el-menu-item>
						</template>
					</el-menu>
				</el-aside>
			</el-container>
			
			<el-main>
				<el-tabs type="border-card" style="height:100%;border:0;">
					<el-tab-pane label="前台菜单" style="padding-top:10px;height:calc(100% - 10px);">
						<el-tabs tab-position="left" style="height:100%;">
							
							<el-tab-pane :label="item.label" :key="item.id" v-for="item in option.data.filter(f => f.type_id === 0 && f.layer_num === 1)">
								<el-collapse v-model="option.collapseB">
									<el-collapse-item name="1" :key="item.id" v-if="item.options.length > 0">
										<template slot="title">
											<span>[ {{item.label}} ]</span>
										</template>
										<el-checkbox v-for="opt in item.options" :key="opt.id" v-model="opt.selected" @change="handleOptionChange({menu_id:item.id, option_id:opt.id, value:opt.value})">
											{{opt.name}}
										</el-checkbox>
									</el-collapse-item>
									<el-collapse-item name="1" :key="imenu.id" v-for="imenu in option.data.filter(f => f.type_id === 0 && f.parent_id === item.id)">
										<template slot="title">
											<span>[ {{imenu.label}} ]</span>
										</template>
										<template v-if="imenu.options.length > 0">
											<el-checkbox v-for="opt in imenu.options" :key="opt.id" v-model="opt.selected" @change="handleOptionChange({menu_id:imenu.id, option_id:opt.id, value:opt.value})">
												{{opt.name}}
											</el-checkbox>
										</template>
									</el-collapse-item>
								</el-collapse>
							</el-tab-pane>
						
						</el-tabs>
					</el-tab-pane>
					<el-tab-pane label="系统菜单" style="padding-top:10px;height:calc(100% - 10px);">
						<el-tabs tab-position="left" style="height:100%;">
							
							<el-tab-pane :label="item.label" :key="item.id" v-for="item in option.data.filter(f => f.type_id === 1 && f.layer_num === 1)">
								<el-collapse v-model="option.collapseB">
									<el-collapse-item name="1" :key="imenu.id" v-for="imenu in option.data.filter(f => f.type_id === 1 && f.parent_id === item.id)">
										<template slot="title">
											<span>[ {{imenu.label}} ]</span>
										</template>
										<template v-if="imenu.options.length > 0">
											<el-checkbox v-for="opt in imenu.options" :key="opt.id" v-model="opt.selected" @change="handleOptionChange({menu_id:imenu.id, option_id:opt.id, value:opt.value})">
												{{opt.name}}
											</el-checkbox>
										</template>
									</el-collapse-item>
								</el-collapse>
							</el-tab-pane>
						
						</el-tabs>
					</el-tab-pane>
				</el-tabs>
			</el-main>
		</el-container>
		<el-dialog :title="role.form.dialog.title" width="25%" :visible.sync="role.form.dialog.visible">
			<avue-form ref="roleForm" :option="role.form.option" v-model="role.form.obj">
			</avue-form>
			<span slot="footer" class="dialog-footer">
        <el-button @click="role.form.dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleRoleSave">确 定</el-button>
      </span>
		</el-dialog>
	</basic-container>
</template>

<script>
  import { getListData as getMenuData } from "../menu/api"
  import {
    getFormOption,
    getMapData,
    getDetailData,
    createAt,
    deleteAt,
    updateAt,
    createRelevantAt,
    deleteRelevantAt
  } from './api'

  const thatRoleFormOption = getFormOption()

  export default {
    name: "admin-role-index",
    components: {},
    data () {
      return {
	      permission: {},
	      options: [],
        role: {
          data: [],
          select: 0,
          form: {
            dialog: {
              title:"",
              visible: false
            },
            option: thatRoleFormOption,
            obj: {
              id: 0
            }
          }
        },
        option: {
          collapseA: ['1'],
          collapseB: ['1'],
          data: [],
          relevant: []
        }
      }
    },
    created () {
      this.handleRoleData()
      // this.handleOptionData()
    },
	  watch: {
		  options() {
			  let btns = {
				  viewBtn:false,
				  addBtn:false,
				  delBtn:false,
				  editBtn:false
			  }
			  this.options.forEach((opt) => {
				  switch (opt) {
					  case 'view':
						  btns.viewBtn = true
						  break
					  case 'create':
						  btns.addBtn = true
						  break
					  case 'delete':
						  btns.delBtn = true
						  break
					  case 'update':
						  btns.editBtn = true
						  break
				  }
			  })
			  this.permission = btns
		  }
	  },
    mounted () {},
    computed: {},
    props: [],
    methods: {
      handleRoleData() {
        getMapData().then(res => {
          this.options = res.data.permissions
          this.role.data = res.data.data
        })
      },
      handleRoleSelect(value) {
        this.role.select = value
        getMenuData({role_id: value})
            .then(res => {
              this.option.data = res.data.data;
            })
      },
      handleOptionData() {
        getMenuData()
            .then(res => {
              this.option.data = res.data.data;
            })
      },
      reloadCheckDefault() {
        this.option.data.forEach(item => {
          item.options.forEach(opt => {
            opt.checked = false
          })
        })
      },
      /**
       * 操作checkbox选中值
       */
      handleOptionChange(opt) {
        opt.role_id = this.role.select
        //选中
        if(event.target.checked === true) {
          //创建角色与菜单操作的关联
          createRelevantAt(opt)
              .then(res => {
                if(res.data.code == 200)
                  this.option.relevant.push(opt)
              })
        }
        //取消选中
        else {
          opt.value = null
          //删除角色与菜单操作的关联
          deleteRelevantAt(opt)
              .then(res => {
                if(res.data.code == 200) {
                  const idx = this.option.relevant.findIndex(f => f.role_id === opt.role_id
                      && f.menu_id === opt.menu_id
                      && f.option_id === opt.option_id)
                  if(idx)
                    this.option.relevant.splice(idx, 1)
                }
              })
        }
      },
      /**
       * 角色 删除
       */
      handleRoleDel(obj, index) {
        //事件冒泡 阻止
        event.cancelBubble = true

        this.$confirm(`是否确认删除名为 '${obj.label}' 的角色`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteAt({id:obj.value})
              .then(() => {
                this.role.data.splice(index, 1)
                this.option.data = []
                this.$message({
                  showClose: true,
                  message: "删除成功",
                  type: "success"
                })
              })
        }).catch(() => { })
      },
      /**
       * 角色 编辑窗打开
       */
      handleRoleFormOpen(title, roleId) {
        if(roleId) {
          //事件冒泡 阻止
          event.cancelBubble = true
          getDetailData({id:roleId}).then(res => {
            this.role.form.obj = res.data.data
            this.role.form.dialog.title = `${title}角色`
            this.role.form.dialog.visible = true
          })
        } else {
          this.role.form.dialog.title = `${title}角色`
          this.role.form.dialog.visible = true
        }
      },
      /**
       * 角色 重置表单
       */
      resetRoleForm() {
        this.role.form.obj = {
          id: 0,
          name:"",
          sort: 99,
          remark: ""
        }
        this.handleRoleData()
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleRoleSave () {
        const formData = this.role.form.obj
        //修改
        if(formData.id) {
          updateAt(formData)
              .then(() => {
                this.$message({
                  showClose: true,
                  message: "修改成功",
                  type: "success"
                })
                this.role.form.dialog.visible = false
                this.resetRoleForm()
              })
        }
        //新增
        else {
          createAt(formData)
              .then(() => {
                this.$message({
                  showClose: true,
                  message: "添加成功",
                  type: "success"
                });
                this.role.form.dialog.visible = false
                this.resetRoleForm()
              })
        }
      },
      /**
       * @title 数据删除
       *
       **/
      handleDel (row) {
        this.$confirm(`是否确认删除名为${row.name}的角色`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          deleteAt({id:row.id})
              .then(() => {
                this.$message({
                  showClose: true,
                  message: "删除成功",
                  type: "success"
                })
              })
        }).catch(() => { });
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>

